import { computed, ref } from 'vue';
import type { TableButtonItem } from '@/components/CTable';
import { IGetFactorMatchListRes } from '@/apis/system/config/model/factorMatchingRule';
import { useMessage } from '@/hooks/useMessage';
import { queryUnConfirmedRuleNum, removeRule } from '@/apis/system/config/factorMatchingRule';
const { createConfirm, createMessage } = useMessage();

export const useOperation = (refresh: Fn) => {
  const addOrEditRuleVisible = ref(false);
  const unconfirmedRuleVisible = ref(false);
  const currentRule = ref({} as IGetFactorMatchListRes);

  /**
   * 新增规则
   */
  const handleAddRule = () => {
    addOrEditRuleVisible.value = true;
    currentRule.value = {} as IGetFactorMatchListRes;
  };

  /**
   * 编辑规则
   * @param row 表格行数据
   */
  const handleEditRule = (row: IGetFactorMatchListRes) => {
    addOrEditRuleVisible.value = true;
    currentRule.value = row;
  };

  /**
   * 删除规则
   * @param row 表格行数据
   */
  const handleDeleteRule = async (row: IGetFactorMatchListRes) => {
    try {
      await createConfirm('确定删除该规则吗？', '删除后不可恢复！', {
        iconType: 'warning'
      });
      await removeRule({ ruleNos: [row.ruleNo] });
      createMessage.success('删除成功！');
      refresh();
    } catch (error) {
      console.log('error', error);
    }
  };

  /**
   * 查看待确认规则
   */
  const handleViewUnconfirmedRule = () => {
    unconfirmedRuleVisible.value = true;
  };

  /**
   *  查询待确认规则条数
   */
  const unConfirmedRuleNum = ref(0);
  const queryUnConfirmedRule = async () => {
    try {
      const res = await queryUnConfirmedRuleNum();
      unConfirmedRuleNum.value = res;
    } catch (error) {
      console.log(error);
    }
  };
  queryUnConfirmedRule();

  const isShowDot = computed(() => {
    return Number(unConfirmedRuleNum.value) > 0;
  });

  /**
   * 配置表格的按钮
   * @param row 表格行数据
   */
  function getTableButtonsConfig(row: IGetFactorMatchListRes): TableButtonItem[] {
    return [
      {
        text: '编辑',
        btnPermission: 'DM_FACTOR_MATCH_RULE_EDIT',
        onClick: () => handleEditRule(row)
      },
      {
        text: '删除',
        btnPermission: 'DM_FACTOR_MATCH_RULE_DELETE',
        onClick: () => handleDeleteRule(row)
      }
    ];
  }

  return {
    addOrEditRuleVisible,
    unconfirmedRuleVisible,
    currentRule,
    isShowDot,
    getTableButtonsConfig,
    handleAddRule,
    handleViewUnconfirmedRule,
    queryUnConfirmedRule
  };
};
